package com.db.mylogger;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.Date;
import java.util.List;

public class MyLogger {

	private List<IAppender> appenders = new CopyOnWriteArrayList<>();

	private Level loggerLevel = Level.DEBUG;
	private final String name;
	

	public MyLogger(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public Level getLoggerLevel() {
		return loggerLevel;
	}

	public void setLoggerLevel(Level loggerLevel) {
		this.loggerLevel = loggerLevel;
	}

	public void debug(String arg0) {
		log(Level.DEBUG, arg0);
	}
	
	public void debug(String arg0, Object arg1) {
		log(Level.DEBUG, formatter(arg0, arg1) );
	}

	public void error(String arg0) {
		log(Level.ERROR, arg0);
	}

	public void error(String arg0, Object arg1) {
		log(Level.ERROR, formatter(arg0, arg1) );
	}

	public void info(String arg0) {
		log(Level.INFO, arg0);
	}

	public void info(String arg0, Object arg1) {
		log(Level.INFO, formatter(arg0, arg1) );
	}
	
	
	private String formatter(String arg0, Object arg1) {
		return arg0.replace("{}", arg1.toString());
	}
	
	public void log(Level level, String arg0) {
		if (level.getValue() < loggerLevel.getValue()){
			return;
		}

		String message = String.format("%tc %s%n[%s] %s", new Date(), name, level, arg0);

		for (IAppender appender : appenders) {
			appender.append(message);
		}
	}

	public void addAppender(IAppender appender) {
		appenders.add(appender);
	}
	
	public void close() {
		for (IAppender appender : appenders) {
			appender.close();
		}
	}
}
